<?php

use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Input;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Route;

require_once app_path().'/pay/dysms/Sms.php';

class HomeController extends BaseController {

	protected $layout = 'layouts.front';

	public function showHome()
	{
		//return View::make('hello');
		if ($this->isMobile()){
			$banners = Banner::where('type','=',2)->get();
		} else {
			$banners = Banner::where('type','=',1)->get();
		}
// 		$content = View::make();
		$content = $this->makeView('front.home');
		$this->layout->content = $content;
		
		//打乱图片
		$banners->shuffle();
		$content->with("banners",$banners);
		
		$this->layout->with('home',true);
		$login = Session::pull("login",false);
		$this->layout->with("login",$login);//是否显示登录页面
		$style = File::get(storage_path("style"));
		$styles = Config::get("mao.home_style");
		$style = $styles[$style];
		//$content->with("style",$style);
		//Input::header("HTTP_USER_AGENT");
		View::share("style",$style);
	}
	
	public function showProducts($id = 0){
		$content = $this->makeView('front.product-list');
		$this->layout->content = $content;
		$query = Products::orderBy("order","desc");
		if (!empty($id)){
			$category = ProductCategorys::find($id);
			
			if (empty($category->parent_id) && count($category->load("children")->children) > 0){
				//父类别
				$params = array_build($category->children, function($key,$value){
					return array($key,$value->id);
				});
				//$params = array_build($category->children, $callback);
				$query->whereIn("category_id",$params);
				$this->layout->with("expandId",$category->id);
			} else {
				//子类别
				$query->where("category_id","=",$id);
				$this->layout->with("expandId",$category->parent_id);
			}
			
			$this->layout->with("category",$category);
			$content->with("contentTitle",$category->name);
		} else {
			$this->layout->with("all",true);
			$content->with("contentTitle","所有商品");
		}
		$products = $query->paginate(30);
		$content->with("products",$products);
	}
	

	/**
	 * 查询产品信息
	 * @param unknown $id
	 */
	public function showProduct($id){
		$content = $this->makeView('front.product');
		$this->layout->content = $content;
		$product = Products::with(array('ext',
				'sizes'=>function($sub){
					$sub->where('quantity', '>', '0');
				},
				'colors'=>function($sub){
					$sub->where('quantity', '>', '0');
				},
		'images' => function($sub){
			$sub->orderBy('order', 'asc');
		}))->withTrashed()->findOrFail($id);
		$content->with("product",$product);
		//查询同类别下的产品
		$rproducts = $this->findRecommendProducts($id, $product->category_id);
		$content->with("recommends",$rproducts);
	}
	
	private function findRecommendProducts($id,$categoryId){
		$size = 4;
		//查询同类别下的产品
		$rproducts = Products::where("category_id",'=',$categoryId)
		->where("id",">",$id)->take($size)->get();
		$rcount = $rproducts->count();
		if ( $rcount < $size){
			$lproducts = Products::orderBy("id","desc")->where("category_id",'=',$categoryId)
			->where("id","<",$id)->take($size - $rcount)->get();
			$rproducts = $rproducts->merge($lproducts);
		}
		return $rproducts;
	}
	
	public function showCart(){
		$content = $this->makeView('front.cart');
		$this->layout->content = $content;
// 		$value = Cookie::get('cart.maggiemaostudio');
		if (array_key_exists('cart_maggiemaostudio',$_COOKIE) && !empty($_COOKIE['cart_maggiemaostudio'])){
			$value = $_COOKIE['cart_maggiemaostudio'];
			$products = json_decode($value,true);
			if (count($products) > 0){
				$product = Products::find($products[0]["id"]);
				if ($product) {
					//查询同类别下的产品
					$rproducts = $this->findRecommendProducts($product->id, $product->category_id);
					$content->with("recommends",$rproducts);
				}
			}
		}
	}
	
	public function postFavorite(){
		//验证用户是否已经收藏过该产品
		$data = array(
			'product_id'=>Input::get('id'),
			'size_id' => Input::get('size_id',0),
			'size' => Input::get('size'),
			'color_id' => Input::get('color_id',0),
			'color' => Input::get('color'),
			'user_id' => Auth::id()
		);
		//检查是否已经添加过该商品
		$favorite = UserFavorite::where('user_id','=',$data['user_id'])
					->where('product_id','=',$data['product_id'])
					->where('size_id','=',$data['size_id'])
					->where('color_id','=',$data['color_id'])->first();
		if (empty($favorite)){
			UserFavorite::create($data);
		}
		return Response::json(array('success'=>true));
	}
	
	public function postLogin(){
		$user = Input::all();
		$validator = Validator::make(
				$user,
				array(
						'mobile' => 'required',
						'password' => 'required',
				)
		);
		
		if ($validator->fails()){
			//Log::info($validator->messages());
			//return $validator->messages();
			//Log::info($user);
			return array('success'=>false,'error'=>'电子邮箱或者密码不合法!');
		} else {
			$mobile = strtolower($user["mobile"]);
			$password = $user["password"];
			if (Auth::attempt(array('mobile' => $mobile,'password' => $password,'active'=>1))){
				$intended = Session::pull("url.intended");
				Log::info($intended);
				return array('success'=>true,'intended'=>$intended);
				
			} else if (Auth::attempt(array('email' => $mobile,'password' => $password,'active'=>1))){
				$intended = Session::pull("url.intended");
				return array('success'=>true,'intended'=>$intended);
				
			} else {
				$user = User::where('mobile', '=', $mobile)->first();
				if ($user == null){
// 					
					$user = User::where('email', '=', $mobile)->first();
				}
				
				if ($user == null){
					return array('success'=>false,'error'=>'该登录账号未注册.');
				}
				
// 				if ($user != null && $user->active == 0){
// 					return array('success'=>false,'error'=>'您的账号还未激活，请前往您注册的邮箱查看激活邮件。');
// 				}
				//$queries = DB::getQueryLog();
				//Log::info($queries);
				return array('success'=>false,'error'=>'密码不正确，如需找回密码，可点击<a id="forgot-password" class="forgot" style="display:inline;">忘记密码?</a>');
			}
		}
	}
	
	public function logout(){
		if (Auth::check()){
			Auth::logout();
		}
		//$filters = Route::findPatternFilters(Request::instance());
		$refer = Request::header("referer","/");
		$root = Request::root();
		$path = str_replace($root, "", $refer);
		
		$authPaths = array(
			"/order-form",
			"/order/pay/return",
			"/user",
			"/user/order-list",
			"/user/address-list",
			"/user/info",
			"/user/favorite-list",
		);
		if (in_array($path, $authPaths)){
			return Redirect::to("/");
		}
		$authRegexPaths = array(
			"/\/order\/pay\/[0-9]+/",
			"/\/user\/order\/[0-9]+/",
		);
		
		foreach($authRegexPaths as $regex){
			if (preg_match($regex,$path)){
				return Redirect::to("/");
			}
		}
		
		return Redirect::to($refer);
	}
	
	public function postForgot(){
		$data = Input::all();
		$validator = Validator::make(
				$data,
				array(
						'mobile'=> 'required',
						'verifyCode'=> 'required',
						'password'=>'required|alpha_dash|confirmed',
				),
				array(
						'mobile.required'=>'手机不能为空',
						'mobile.numeric' =>'手机号不能存在数字以外的字符',
						'password.required' => '密码不能为空',
						'password.alpha_dash' => '密码只能为数字,[a-zA-Z],下划线,破折号',
						'password.confirmed' => '密码和确认密码不匹配',
						'verifyCode.required' => '验证码不能为空',
				)
		);
		
		if ($validator->fails()){
// 			return array('success'=>false,'error'=>'电子邮箱不合法!');
			return array('success'=>false,'errors'=>$validator->messages()); 
		} else {
			$mobile = strtolower($data["mobile"]);
			$user = User::where("mobile","=",$mobile)->first();
			if (empty($user)){
				return array('success'=>false,'errors' => array(
					'mobile' => array("手机号未注册")
				));
			} else {
				$password = array('password' => Hash::make($data['password']));
				$user->update($password);
				
// 				$email = $user->email;
// 				$name = $user->name;
// 				//单位秒
// 				$expire = time() + Config::get("mao.expire-reset-password") * 60;
// 				$refer = Request::header("referer","/");
// 				//随机一个字符串作为key，用来处理reset有效性和一次性
// 				$resetKey = Config::get("mao.reset_key");
// 				$tokenValue = Crypt::encrypt($user->id.'$'.$email.'$'.$expire.'$'.$resetKey.'$'.$refer);
// 				$token = array('token'=>$tokenValue);
// 				Mail::queue('emails.forgot-password', $token, function($message) use ($email,$name){
// 					$message->to($email, $name)->subject('密码重置申请');
// 				});
				return array('success'=>true);
			}
		}
	}
	
	public function showResetPassword($token){
		
		//用户进行激活用户
		if (empty($token)){
			return "未激活，无效URL";
		}
		//解密
		$token = Crypt::decrypt($token);
		$params = explode('$', $token);
		if (count($params) != 5){
			return "无效URL";
		}
		
		//验证有效性，验证是否有reset-password-key
		$resetKey = Config::get("mao.reset_key");
		if (time() > $params[2] || $resetKey != $params[3]){
			return "该链接已经失效，请重新申请";
		}
	
		$user = User::find($params[0]);
		if (empty($user)){
			return "无效URL,该用户已经不存在";
		}
		
		if ($user->active != 1 ||
			$user->email != $params[1]){
			return "无效用户,或者该用户未激活";
		}
		//$content = View::make();
		$content = $this->makeView('front.reset-password');
		$this->layout->content = $content;
		$content->with("referer",$params[4]);
		$content->with('user',$user);
	}
	
	public function postResetPassword(){
		$data = Input::all();
		$validator = Validator::make(
				$data,
				array(
						'password'=>'required|alpha_dash|confirmed',
				)
		);
		if ($validator->fails()){
			return array('success'=>false,'errors'=>$validator->messages());
		} else {
			$id = $data['id'];
			$password = array('password' => Hash::make($data['password']));
			$user = User::find($id);
			$user->update($password);
			Session::forget('reset-password-key');
			$referer = $data['referer'];
			return Redirect::to($referer);
		}
	}
	
	/**
	 * 发送验证码
	 */
	public function sendVerifyCode(){
		$data = Input::all();
		$validator = Validator::make(
				$data,
				array(
						'mobile'=> 'required|numeric',
				)
		);
		if ($validator->fails()){
			return array('success'=>false,'errors'=>$validator->messages());
		} else {
			try {
				$mobile = $data['mobile'];
					
				$verifyCode = substr(strval(rand(10000,19999)),1,4);
					
				$config = Config::get("mao.sms.config");
				$sms = new Sms($config);
				$templateCode = Config::get("mao.sms.verify");
				$param = array(
						'code' => $verifyCode
				);
				$sms->send($mobile,$templateCode,$param);
				Session::put('mobile_verify_code',$verifyCode);
			} catch (Exception $e){
				Log::error($e);
			}
			
			return array('success' => true);
		}
	}
	
	public function postRegister(){
		$data = Input::all();
		$validator = Validator::make(
				$data,
				array(
						'name' => 'required|max:32',
						'mobile'=> 'required|numeric|unique:users',
						'verifyCode'=> 'required',
						'password'=>'required|alpha_dash|confirmed',
				),
				array(
						'name.required' =>'姓名不能为空',
						'name.max'=>'姓名不能超过:max字符',
						'mobile.required'=>'手机不能为空',
						'mobile.numeric' =>'手机号不能存在数字以外的字符',
						'mobile.unique' => '该手机已注册',
						'email.required' => '邮箱不能为空',
						'email.email' => '邮箱格式不正确',
						'email.unique' => '该邮箱已注册',
						'password.required' => '密码不能为空',
						'password.alpha_dash' => '密码只能为数字,[a-zA-Z],下划线,破折号',
						'password.confirmed' => '密码和确认密码不匹配',
						'verifyCode.required' => '验证码不能为空',
						
						
				)
		);
		if ($validator->fails()){
			return array('success'=>false,'errors'=>$validator->messages());
		} else {
			$sessionVerifyCode = Session::get("mobile_verify_code");
			if ($data["verifyCode"] != $sessionVerifyCode){
				return array(
					'success'=>false,
					'errors'=>array(
					"verifyCode" => array('验证码错误')
				));
			}
			
			DB::transaction(function() use ($data){
				//邮箱需要进行小写转换
				$data['email'] = strtolower($data["email"]);
// 				$data['email'] = "";
				$data['active'] = 1;
				$data['admin'] = 0;
				$data['subscribe'] = 0;
				$data['password'] = Hash::make($data['password']);
				unset($data['password_confirmation']);
				unset($data['verifyCode']);
				$user = User::create($data);
				// 熊旭发送注册邮件
// 				$email = $user->email;
// 				$name = $user->name;
// 				$refer = Request::header("referer","/");
// 				$tokenValue = Crypt::encrypt($user->id.'$'.$email.'$'.$name.'$'.$user->mobile.'$'.$refer);
// 				$token = array('token'=>$tokenValue);
// 				Mail::queue('emails.register', $token, function($message) use ($email,$name){
// 					$message->to($email, $name)->subject('欢迎来到MAGGIEMAO蔓茂花廊');
// 				});
			});
			return array('success'=>true);
		}
	}
	
	public function doActiveRegister($token){
		//用户进行激活用户
		if (empty($token)){
			return "未激活，无效URL";
		}
		//解密
		$token = Crypt::decrypt($token);
		$params = explode('$', $token);
		if (count($params) != 5){
			return "无效URL";
		}
		
		$user = User::find($params[0]);
		if (empty($user)){
			return "无效URL,该用户已经不存在";
		}
		
		if ($user->active == 0 && 
			$user->email == $params[1] &&
			$user->name == $params[2] &&
			$user->mobile == $params[3]){
			$user->update(array('active' => 1));
		}
		//重定向到首页
// 		return Redirect::to($params[4]);
		return Redirect::to("/");
	}

	
	public function showOrderForm() {
		$content = $this->makeView('front.order-form');
		$this->layout->content = $content;
		
		//1.没有产品不能进行下订单
		if (!array_key_exists('cart_maggiemaostudio',$_COOKIE)){
			return Redirect::to('product-list');
		}
		$userId = Auth::id();
		$addresses = UserAddress::where('user_id','=',$userId)->get();
		$content->with('addresses',$addresses);
	}
	
	
	public function postSearch(){
		$q = Input::get('q',"");
		$q = trim($q);
		if (empty($q)){
			return Redirect::to('product-list');
		}
		//Crypt::setMode(MCRYPT_MODE_ECB);
		$q = Crypt::encrypt(str_limit($q,32,''));
		//return Redirect::to('search',array('q'=>$q));
		return Redirect::action('HomeController@showSearch', $q);
	}
	
	public function showSearch($q){
		//将查询
		if (empty($q)){
			return Redirect::to('product-list');
		}
		//Crypt::setMode(MCRYPT_MODE_ECB);
		$q = Crypt::decrypt($q);
		$products = Products::orderBy('id','desc')->where('name','like','%'.$q.'%')->orWhere('brand', 'like','%'.$q.'%')->paginate(24);
		$content = $this->makeView('front.product-list');
		$this->layout->content = $content;
		$content->with("search",true);
		$content->with("contentTitle",$q);
		$content->with("products",$products);
	}
	
	public function showAbout(){
		$content = $this->makeView('front.footer.about');
		$this->layout->content = $content;
	}
	
	public function showContact(){
		$content = $this->makeView('front.footer.contact');
		$this->layout->content = $content;
	}
	
	public function showFaq(){
		$content = $this->makeView('front.footer.faq');
		$this->layout->content = $content;
	}
	
	public function showGuide(){
		$content = $this->makeView('front.footer.guide');
		$this->layout->content = $content;
	}
	
	public function showPrivacy(){
		$content = $this->makeView('front.footer.privacy');
		$this->layout->content = $content;
	}
	
	public function showTerms(){
		$content = $this->makeView('front.footer.terms');
		$this->layout->content = $content;
	}
	
	/**
	 * 显示stories
	 */
	public function showStories(){
		$id = Input::get("id",0);
		$content = $this->makeView('front.story');
		$this->layout->content = $content;
		$stories = Story::orderBy("id","desc")->get();
		
		if ($id == 0){
			$story = $stories->first();
			$content->with("story",$story);
		} else {
			$story = $stories->get($id);
			$story;
			$stories->each(function($s) use ($id,&$story){
				if ($s->id == $id){
					$story = $s;
				}
			});
			$content->with("story",$story);
		}
		
		$this->layout->with("storyId",$id);
		
		$content->with("stories",$stories);
		
	}
}
